// src/http/axios.js
import axios from 'axios';
import router from '@/router';
import store from '@/store/index.js';

axios.defaults.timeout = 10000 // 请求超时时间

const AJAX = axios.create({
	baseURL: process.env.NODE_ENV === 'production' ? window.location.origin + '/api' : import.meta.env.VITE_APP_DOMAIN_URL,
	headers: {
		"Content-Type": "application/json;charset=UTF-8"
	}
})

// axios 请求拦截器
AJAX.interceptors.request.use(
	config => {
		if (localStorage.getItem("token")) {
			config.headers.token = localStorage.getItem('token');
		}
		if (config.showLoading !== false) {
			store.commit('showLoading');
		}
		
		// const currentLanguage = i18n.locale;
		// // 将语言代码添加到请求头或参数中
		// config.headers['Accept-Language'] = store.state.lang;
		return config
	}, error => {
		return Promise.reject(error)
	}
)

// 响应拦截器
let cont = 0
AJAX.interceptors.response.use(
	res => {
		store.commit('hideLoading');
		return res.data;
	},
	error => {
		store.commit('hideLoading');
		const code = error.response.status;

		if (code == 401) {
			localStorage.removeItem('token');
			if (router.currentRoute.value.path != '/login') {
				router.push('/login');
			}
			cont++
		}

		return Promise.reject(error.response.data)
	}
)

export default AJAX;